<template>
  <div
    ref="vidoeItem"
    :style="{ height: '100vh' }"
    class="video videoItem"
    v-if="isShow"
  >
    <!-- v-if="item.detail && item.detail.newsContent" -->
    <!-- <div v-if="index == 0 && !playing" class="poster"><img :src="getPoster(item)" alt=""></div> -->
    <!-- <div v-if="!playing" class="poster"><img :src="getPoster(item)" alt=""></div> -->
    <div class="self">
      <div class="video-player">
        <div
          @click="doPlay"
          class="video-player video-player-item"
          :id="'videoItem_' + videoPlayerIndex + '_' + index"
          :style="[{ 'background': '#000' }]"
        ></div>
          <!-- :style="[{ 'background': '#000' }]" -->
          <!-- :style="[{ 'background': playing ? '#000' : 'url(' + getPoster(item) + ') no-repeat center' }]" -->
      </div>
      <likeUpsComponent
        class="left-bar"
        :personfocus="focusTime"
        @focus="focus"
        :key="'like' + index"
        v-if="item"
        :data="item"
      ></likeUpsComponent>
    </div>
    <div class="video-title">
      <p @click="goUserInfo" class="text">
        <span class="inner-text" v-show="nickName!=''">@{{ nickName }}</span>
      </p>
      {{ getVideoTitle(item) }}
    </div>
  </div>
</template>


<script>
/* eslint-disable quotes */

import likeUpsComponent from "@/components/common/likeUpsComponent.vue";
import $ from "../../../../../static/js/jquery-1.12.4.min";
import _ from "lodash";
import Axios from "axios";
let playEndFn = null;
let timeupdateFn = null;
/**
 * currentVideoPlayerIndex:当前标签
 * videoPlayerIndex:标签排序
 */
export default {
  components: { likeUpsComponent },
  name: "videoItem",
  props: ["data", "index", "currentVideoIndex", "focusTime", "videoPlayerIndex", "currentVideoPlayerIndex","isDormancy"],
  data() {
    return {
      isShow: false,
      player: null,
      playing: false,
      isFullScreen: false,
      preload: false,
      nickName: "",
      list: [],
      item: {},
      detail: {},
      options: {
        pullUpLoad: true,
        scrollbar: false,
      },
      userInfo: {},
      newsDetail: {
        newsContent: null,
        files: null,
        upOrDown: null,
        collected: null,
      },
    };
  },
  watch: {
    //是否休眠，值为true停止当前tab下所有视频播放
    isDormancy(newVal, oldVal) {
      console.log('头部标签切换值：' + newVal)
      this.$nextTick(()=>{
        if (newVal) {
          this.player && this.player.pause();
          this.player && (this.player.mypause = true);
        }else{
          if (this.currentVideoIndex === this.index) {
            console.log(`播放视频的`)
            this.player && this.player.play();
            this.addVideoAttr("videoItem_" + this.videoPlayerIndex + "_" + this.index);
            // this.historyAdd();
          }
        }
      })
    },
    currentVideoIndex(newVal, oldVal) {
      this.$nextTick(()=>{
        if (newVal === this.index) {
          // this.historyAdd();
          // console.log("watch--开始播放", this.index);
          // $("#videoItem_" + this.index + '_pause').attr('id','videoItem_'+ this.index);
        } else {
          this.player && this.player.pause();
          this.player && (this.player.mypause = false);
          // console.log("watch--暂停播放", this.index);
          // $("#videoItem_" + this.index).attr('id','videoItem_'+ this.index + '_pause');
          // this.player.seek(0);
        }
      })
      this.needPreload(newVal);
    },
  },
  created() {
    this.isShow = true;
  },
  mounted() {
    this.$nextTick(()=>{
      if (this.videoPlayerIndex=='100') {
          this.userInfo = this.$localStorage.get("userInfo");
          this.detail = _.extend({}, this.data);
          this.needPreload(0);
          this.fetchDetail(this.data.id);
      } else {
        if (this.currentVideoIndex == this.index) {
          this.userInfo = this.$localStorage.get("userInfo");
          this.detail = _.extend({}, this.data);
          this.needPreload(0);
          this.fetchDetail(this.data.id);
        }
      }
    })
  },
  activated() {
    this.isShow = true;
    console.log('videoItem------activated',this.index)
    if (!this.isDormancy) { //激活状态
      if (this.currentVideoIndex === this.index) {
        // this.historyAdd();
        this.player && this.player.play();
        this.addVideoAttr("videoItem_" + this.videoPlayerIndex + "_" + this.index);
      }
    }
  },
  beforeDestroy() {
    this.player && this.player.pause();
    this.player && this.player.dispose();
    this.player = null;
    if (this.currentVideoIndex == this.index) {
      console.log('tab：' + this.videoPlayerIndex + "，当前：" + this.currentVideoIndex + "销毁");
      this.isShow = false;
    }
  },
  methods: {
    addVideoAttr(id) {
      /*非苹果就不用以下操作*/
      if (!window.webkit) {
        return false;
      }
      /*在苹果上刷抖音时出现有的宽屏视频挡住右侧信息*/
      setTimeout(() => {
        let el = document.getElementById(id);
        if (!el) {
          return false;
        }
        let myvideo = el.querySelector("video");
        if (!el) {
          return false;
        }
        myvideo.setAttribute("x5-video-player-type", "h5");
        myvideo.setAttribute("x5-video-player-fullscreen", "true");
        myvideo.setAttribute("x-webkit-airplay", "true");
        myvideo.setAttribute("webkit-playsinline", "");
        myvideo.setAttribute("playsinline", "");
        myvideo.style.opacity = 0;
        setTimeout(() => {
          myvideo.style.opacity = 1;
        }, 300);
      }, 0);
    },
    // 暴露给父级调用
    pause(){
      this.player.pause();
      console.log('停止播放')
    },
    /*阿里播放器*/
    aliplay(data) {
      let isAutoplay = this.index == this.currentVideoIndex;
      let me = this;
      this.player = new Aliplayer(
        {
          id: "videoItem_" + this.videoPlayerIndex + "_" + me.index,
          cover:"",
          source: this.getVideoSrc(data.files),
          preload: true,
          playsinline: true,
          useH5Prism: true,
          skinLayout: [
            // { name: "bigPlayButton", align: "blabs", x: 30, y: 80 },
            {
              name: "H5Loading",
              align: "cc",
            },
            /* { name: "errorDisplay", align: "tlabs", x: 0, y: 0 },
            { name: "infoDisplay" },
            { name: "tooltip", align: "blabs", x: 0, y: 56 },
            { name: "thumbnail" }, */
            {
              name: "controlBar",
              align: "blabs",
              x: 0,
              y: 0,
              children: [
                { name: "progress", align: "blabs", x: 0, y: 44 },
                // { name: "playButton", align: "tl", x: 15, y: 12 },
                { name: "timeDisplay", align: "tl", x: 10, y: 7 },
                // { name: "fullScreenButton", align: "tr", x: 10, y: 12 },
                // { name: "subtitle", align: "tr", x: 15, y: 12 },
                // { name: "setting", align: "tr", x: 15, y: 12 },
                // { name: "volume", align: "tr", x: 5, y: 10 },
              ],
            },
          ],
          autoplay: isAutoplay,
          rePlay: true,
          controlBarVisibility: "click",
          showBarTime: "10000",
          x5_type: "h5",
          x5_fullscreen: true,
          x5LandscapeAsFullScreen: false,
          //          width: '100%',
          height: "100%",
        },
        function (player) {
          $("#videoItem_" + me.videoPlayerIndex + "_" + me.index + " video").attr("poster","static/images/dangjian/video/backgroud-poster.png")
          if (me.index === me.currentVideoIndex) {
            this.player.play();
            me.addVideoAttr("videoItem_" + me.videoPlayerIndex + "_" + me.index);
          }
        }
      );
      this.$nextTick(()=>{
        if (this.isDormancy && this.player) {
              this.player && this.player.pause();
              this.player.mypause = false;
        }
      })
      $('.prism-error-operation').hide();
      $('.prism-error-content p').hide();
      $('.prism-error-content').append('<p style="margin-top: 50px;">播放出错啦！</p>');
      this.videoPlayerEvent(this.player);
    },
    /*阿里播放的事件、方法*/
    videoPlayerEvent(player) {
      let playBtn = `<div class="prism-big-play-btn center" style="display: none;"><div class="outter"></div></div>`;
      let me = this;
      $("#videoItem_" + this.videoPlayerIndex + "_" + this.index)
        .append(playBtn)
        .on("click", function () {
          if (player.getStatus() !== "playing") {
            player.mypause = true; // 手动暂停时需要接着播放
            player.play();
            $(this).find(".prism-big-play-btn").fadeOut(500);
          } else {
            player.pause();
            $(this).find(".prism-big-play-btn").show();
          }
        });
      player.on("ended", () => {
        console.log("video ended");
        this.onended();
      });
      player.on("play", () => {
        this.historyAdd();
        console.log("video play", me.index);
        $("#videoItem_" + this.videoPlayerIndex + "_" + this.index)
          .find(".prism-big-play-btn")
          .hide();
        // 每次播放得重头开始
        if (!player.mypause) {
          player.seek(0);
        }
        player.mypause = false;
        me.onplay();
        me.addVideoAttr("videoItem_" + this.videoPlayerIndex + "_" + me.index);
      });
      player.on("pause", () => {
        console.log("video pause", me.index);
      });
      let consoleTime = Date.now();
      player.on("timeupdate", () => {
        if (this.currentVideoPlayerIndex!='-1') {
          /*关闭不是该播放的视频*/
          if (this.currentVideoIndex != this.index || this.videoPlayerIndex != this.currentVideoPlayerIndex) {
            console.log("timeupdate", player.getCurrentTime(),`当前标签:${this.currentVideoPlayerIndex},标签排序:${this.videoPlayerIndex},当前播放:${this.currentVideoIndex},视频排序:${this.index}个，isDormancy:${this.isDormancy},暂停`);
            player.pause();
          }
          if (Date.now() - consoleTime > 3 * 1000) {
            console.log("timeupdate", player.getCurrentTime(),`当前标签:${this.currentVideoPlayerIndex},标签排序:${this.videoPlayerIndex},当前播放:${this.currentVideoIndex},视频排序:${this.index}个，isDormancy:${this.isDormancy}`);
            consoleTime = Date.now();
          }
        }
      });
    },
    listenVideo() {
      // 用阿里的播放器
      return false;
      let time = Date.now();
      let me = this;
      function reTryListen() {
        let nowTime = Date.now();
        if (nowTime - time > 3000) {
          console.log("视频监听失败");
          return false;
        }
        setTimeout(() => {
          let myVideo = document.querySelector("#videoItem_" + me.videoPlayerIndex + "_" + me.index);
          if (!myVideo) {
            console.log("视频监听");
            return reTryListen();
          }
          myVideo.addEventListener("ended", () => {
            me.onended();
          });
          if (!timeupdateFn) {
            function timeupdate(e) {
              let myVideo = document.querySelector("video");
              console.log("timeupdate");
              if (myVideo && myVideo.duration <= myVideo.currentTime + 0.5) {
                console.log("myVideo ended");
                console.log(e);
                me.onended();
              }
            }
            timeupdateFn = timeupdate;
          }
          if (!playEndFn) {
            playEndFn = function () {
              me.onended();
            };
          }
          myVideo.removeEventListener("timeupdate", timeupdateFn);
          myVideo.addEventListener("timeupdate", timeupdateFn);
          myVideo.addEventListener("play", () => {
            me.onplay();
          });
          myVideo.play();
        }, 100);
      }
      reTryListen();
    },
    focus() {
      this.$emit("focus");
    },
    onended() {
      // 两次播放完成时间不可能低于2分钟
      clearTimeout(this.$refs.vidoeItem.watchTimer);
      console.log("emit ended");
      this.$refs.vidoeItem.watchTimer = setTimeout(() => {
        this.$emit("ended");
      }, 1000);
    },
    needPreload(newVal) {
      if (this.index - newVal < 2) {
        this.preload = true;
      }
    },
    doPlay(data) {},
    play(e) {
      if (this.player) {
        return this.player.play();
      }
      /* if (!e) {
        return document.querySelector("#videoItem_" + this.videoPlayerIndex + "_" + this.index).play();
      }
      e.target.play(); */
    },
    onplay(e) {
      if (e) {
        e.target.currentTime = 0;
      }
      this.$emit("onplay");
      setTimeout(() => {
        this.listenVideo();
        this.playing = true;
      $("#videoItem_" + this.videoPlayerIndex + "_" + this.index).find(".prism-big-play-btn").hide();
      }, 5);
    },
    goUserInfo() {
      if (this.detail.createUser) {
        this.$router.push({
          name: "microVideo",
          query: { userId: this.detail.createUser },
        });
      }
    },
    getUserName(item) {
      return (
        this.nickName ||
        item.detail.newsContent.nickname ||
        item.detail.newsContent.createUserName ||
        item.createUserName ||
        "未知"
      );
    },
    /*拉取用户信息*/
    fetchUserInfo(userid) {
      this.fetchService.getUserInfo(userid).then((res) => {
        this.nickName = res.qq || res.fullname;
      });
    },
    getVideoTitle(item) {
      return item.detail && item.detail.newsContent.title;
    },
    getPoster(item) {
      if (this.tools.indexOfHttp(item.listPicUrl)){
        return item.listPicUrl
      }
      return this.tools.getImgUrl(item.listPic);
    },
    // 添加到我的足迹
    historyAdd () {
      let data = {
        contentId: this.item.detail.newsContent.id,
        newsType: 3,  // 新闻类型(0图文;1长视频;2音频;3短视频)
      }
      this.fetchService.historyAdd(data).then((res) => {
      })
    },
    fetchDetail(id) {
      let me = this;
      return Axios.all([
        me.contentDetailNew(id),
        me.newsFiles(id),
        me.contentGetSfdz(id),
        me.contentGetSfsc(id),
      ])
        .then(
          Axios.spread((res1, res2, res3, res4) => {
            me.newsDetail.newsContent = res1;
            me.newsDetail.files = res2;
            me.newsDetail.upOrDown = res3;
            me.newsDetail.collected = res4;

            me.item = _.extend({}, me.data);
            me.item.detail = me.newsDetail;
            me.$nextTick(() => {
              // me.aliplay(me.item);
              me.aliplay(me.newsDetail); //JJ 2020年12月16日 10:00:26 使用file的地址
            });
            me.fetchUserInfo(res1.createUser);
          })
        )
        .catch((err) => {
          console.log(err.response);
        });
    },
    //获取内容详情(新)
    contentDetailNew(id) {
      let me = this;
      return me.fetchService.contentDetailNew(id).then((res) => {
        if (res.code === 0) {
          return res.data.newsContent;
        }
      });
    },
    //获取新闻附件
    newsFiles(id) {
      let me = this;
      return me.fetchService.newsFiles(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //查询当前用户是否点赞指定的新闻
    contentGetSfdz(id) {
      let me = this;
      return me.fetchService.contentGetSfdz(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //查询当前用户是否收藏指定的新闻
    contentGetSfsc(id) {
      let me = this;
      return me.fetchService.contentGetSfsc(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    getVideoSrc(item) {
      if (item.length === 0) {
        return "";
      }
      if (this.tools.indexOfHttp(item[0].fileOssUrl)){
        return item[0].fileOssUrl
      }
      return this.tools.getImgUrl(item[0].fileId);
    },
  },
};
</script>


<style scoped lang="scss">
@import "@/common/stylus/moon.scss";
*::-webkit-media-controls-start-playback-button {
  display: block;
  -webkit-appearance: block;
}
*::-webkit-media-controls-panel {
  display: block;
  -webkit-appearance: block;
}

*::--webkit-media-controls-play-button {
  display: block;
  -webkit-appearance: block;
}
.video {
  video {
    /*opacity: 0;*/
  }
  .poster {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 3;
    overflow: hidden;
    background-color: $theme-color;
    img {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 100%;
      height: auto;
    }
  }
  .self {
    position: relative;
    z-index: 1;
    width: 100%;
    height: 100%;
    .left-bar {
      position: absolute;
      z-index: 77 !important;
    }
  }
}
.full-page {
  padding: 0;
  height: 100vh;
  .head-wrap,
  .top-menu,
  .btn-menu {
    display: none;
  }
  .cube-slide-group,
  .cube-slide-item,
  .video {
    height: 100vh !important;
  }
}
.video-wrap .video .video-title {
  width: 70%;
  .text{
    min-height: pxToRem(48px);
    line-height: pxToRem(48px);
  }
}
.video-player {
  background-size: 100% auto !important;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1 !important;
  width: 100%;
  height: 100%;
  video {
    z-index: 1 !important;
  }
}
</style>

